<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useQuasar } from 'quasar';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';

// 导入pdfMake
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFontsModule from 'pdfmake/build/vfs_fonts';
import ProblemSolver from './ProblemSolver.vue';

const $q = useQuasar();
const userStore = useUserStore();
const router = useRouter();

// 中文字体加载状态
const chineseFontLoaded = ref(false);
// 记录字体路径
const chineseFontPath = `${import.meta.env.BASE_URL}fonts/simsun.ttf`;

// 直接赋值
pdfMake.vfs = pdfFontsModule;

console.log('pdfFonts.vfs keys:', pdfFontsModule && Object.keys(pdfFontsModule));
console.log('pdfFontsModule:', pdfFontsModule);
console.log('pdfFontsModule.default:', pdfFontsModule.default);

// 1. 首先在文件顶部定义一个常量保存基础字体
const DEFAULT_FONT_NAME = 'simsun.ttf';

// 添加反馈对话框的显示状态
const showFeedbackDialog = ref(false);
const feedbackContent = ref('');
const feedbackEmail = ref('');

// 添加使用说明对话框的显示状态
const showInstructionsDialog = ref(false);

// 添加在线答题对话框的显示状态
const showProblemSolver = ref(false);

// 在组件挂载时加载中文字体
onMounted(async () => {
  await loadChineseFont();
});

// 加载并注册中文字体
const loadChineseFont = async () => {
  console.log('pdfFonts.vfs:', pdfFontsModule);
  if (!pdfMake.vfs) {
    throw new Error('pdfMake.vfs 依然未初始化，pdfFonts.vfs 也为 undefined！');
  }
  console.log('loadChineseFont 前 vfs:', pdfMake.vfs);
  try {
    
    console.log(`完整字体路径: ${chineseFontPath}`);
    
    // 先检查字体文件是否存在
    const exists = await checkFontFile(chineseFontPath);
    if (!exists) {
      throw new Error(`字体文件不存在: ${chineseFontPath}`);
    }
    
    console.log('字体文件存在，开始加载');
    
    // 加载中文字体文件
    const response = await fetch(chineseFontPath);
    if (!response.ok) {
      throw new Error(`字体文件请求失败: ${response.status} ${response.statusText}`);
    }
    
    // 获取字体的ArrayBuffer
    const fontData = await response.arrayBuffer();
    console.log(`字体文件已加载, 大小: ${fontData.byteLength} 字节`);
    
    if (fontData.byteLength === 0) {
      throw new Error('字体文件大小为0，可能未正确加载');
    }
    
    // 转换为Base64
    const base64Font = bufferToBase64(fontData);
    console.log(`字体已转换为Base64, 长度: ${base64Font.length}`);
    
    // 只注册自定义字体，不要再赋值 vfs
    pdfMake.vfs[DEFAULT_FONT_NAME] = base64Font;
    pdfMake.fonts = {
      ...pdfMake.fonts,
      SimSun: {
        normal: DEFAULT_FONT_NAME,
        bold: DEFAULT_FONT_NAME,
        italics: DEFAULT_FONT_NAME,
        bolditalics: DEFAULT_FONT_NAME
      }
    };

    // 验证字体注册 - 只验证中文字体
    const verification = {
      'vfs是否存在': !!pdfMake.vfs,
      'vfs中的字体': Object.keys(pdfMake.vfs),
      'fonts配置': pdfMake.fonts,
      'SimSun字体是否存在': !!pdfMake.vfs[DEFAULT_FONT_NAME],
      'SimSun字体内容长度': pdfMake.vfs[DEFAULT_FONT_NAME]?.length
    };
    
    console.log('字体注册后的详细状态:', verification);
    
    // 只验证中文字体是否存在
    if (!pdfMake.vfs[DEFAULT_FONT_NAME]) {
      throw new Error('中文字体注册失败');
    }

    chineseFontLoaded.value = true;
    
    
    return true;
  } catch (error) {
    console.error('字体加载错误:', error);
    chineseFontLoaded.value = false;
    
    // 显示更详细的错误信息
    $q.notify({
      message: `字体加载错误: ${(error as any).message}`,
      color: 'negative',
      timeout: 5000,
      position: 'top'
    });
    
    return false;
  }
};

// ArrayBuffer转Base64
function bufferToBase64(buffer: ArrayBuffer): string {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

// 检查字体文件是否存在
const checkFontFile = async (path: string): Promise<boolean> => {
  try {
    const response = await fetch(path, { method: 'HEAD' });
    return response.ok;
  } catch {
    return false;
  }
};

// 配置组类型定义
type ConfigGroup = {
  id: number;
  count: number;  // 题目数量
  customRange: number;  // 自定义范围
  rangeType: string;  // 预设或自定义
  operations: {
    addition: boolean;
    subtraction: boolean;
    multiplication: boolean;
    division: boolean;
  };
  excludeDuplicates: boolean;
  allowRemainder: boolean;
  multiplicationTableLimit: boolean;
  noCarryAddition: boolean;
  noBorrowSubtraction: boolean;
  // 位数限制（用于乘除法）
  useDigitLimit: boolean;  // 是否使用位数限制
  multiplicandDigits: string;  // 被乘数位数：'1' 一位数, '2' 两位数, 'any' 任意
  multiplierDigits: string;  // 乘数位数：'1' 一位数, '2' 两位数, 'any' 任意
  dividendDigits: string;  // 被除数位数：'1' 一位数, '2' 两位数, 'any' 任意
  divisorDigits: string;  // 除数位数：'1' 一位数, '2' 两位数, 'any' 任意
};

// 参数配置（单一配置模式）
const config = reactive({
  numberRange: 10,  // 默认10以内
  customRange: 20,  // 自定义范围
  rangeType: '10',  // 预设或自定义
  operations: {     // 运算类型改为复选框
    addition: true,   // 默认选中加法
    subtraction: true, // 默认选中减法
    multiplication: false,
    division: false
  },
  problemCount: '20',  // 默认20题，修改为字符串以匹配单选框值
  customCount: 50,   // 自定义题数
  countType: '20', // 修改为与problemCount相同的初始值
  excludeDuplicates: true, // 排除重复算式
  allowRemainder: false,  // 除法是否允许余数
  multiplicationTableLimit: false, // 乘法口诀表范围限制
  noCarryAddition: false, // 无进位加法
  noBorrowSubtraction: false, // 无退位减法
  showAnswers: false,  // 是否显示参考答案
  // 位数限制（用于乘除法）
  useDigitLimit: false,  // 是否使用位数限制
  multiplicandDigits: 'any',  // 被乘数位数
  multiplierDigits: 'any',  // 乘数位数
  dividendDigits: 'any',  // 被除数位数
  divisorDigits: 'any',  // 除数位数
});

// 多配置组模式
const useMultiConfig = ref(false); // 是否使用多配置组模式
const configGroups = ref<ConfigGroup[]>([
  {
    id: 1,
    count: 40,
    customRange: 100,
    rangeType: '100',
    operations: {
      addition: true,
      subtraction: true,
      multiplication: false,
      division: false
    },
    excludeDuplicates: true,
    allowRemainder: false,
    multiplicationTableLimit: false,
    noCarryAddition: false,
    noBorrowSubtraction: false,
    useDigitLimit: false,
    multiplicandDigits: 'any',
    multiplierDigits: 'any',
    dividendDigits: 'any',
    divisorDigits: 'any'
  }
]);
let nextConfigGroupId = 2;

// 监听并限制自定义范围不超过10000
watch(() => config.customRange, (newValue) => {
  if (newValue > 10000) {
    config.customRange = 10000;
  }
});

// 监听并限制自定义题目数量不超过10000
watch(() => config.customCount, (newValue) => {
  if (newValue > 10000) {
    config.customCount = 10000;
  }
});

// 监听配置组的变化，限制范围
watch(() => configGroups.value, (newGroups) => {
  newGroups.forEach(group => {
    if (group.customRange > 10000) {
      group.customRange = 10000;
    }
    if (group.count > 10000) {
      group.count = 10000;
    }
    if (group.count < 1) {
      group.count = 1;
    }
  });
}, { deep: true });

// 生成的题目列表
const problems = ref<Array<{
  expression: string,
  answer: number,
  displayExpression: string
}>>([]);

// 根据配置生成随机数
const generateRandomNumber = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

// 计算数字范围
const numberRangeValue = computed(() => {
  if (config.rangeType === 'custom') {
    return config.customRange;
  } else {
    // 将范围类型字符串转换为数字
    return parseInt(config.rangeType, 10);
  }
});

// 计算题目数量
const problemCountValue = computed(() => {
  if (config.countType === 'custom') {
    return config.customCount;
  } else {
    // 将数量类型字符串转换为数字
    return parseInt(config.countType, 10);
  }
});

// 辅助函数：检查加法是否有进位
const hasCarry = (a: number, b: number): boolean => {
  // 转换为字符串，便于按位检查
  const aStr = a.toString();
  const bStr = b.toString();
  
  let carry = 0;
  // 从个位开始检查每一位
  for (let i = 0; i < Math.max(aStr.length, bStr.length); i++) {
    // 获取当前位的数字，不存在则为0
    const digitA = i < aStr.length ? parseInt(aStr[aStr.length - 1 - i]) : 0;
    const digitB = i < bStr.length ? parseInt(bStr[bStr.length - 1 - i]) : 0;
    
    // 判断是否进位
    if (digitA + digitB + carry >= 10) {
      return true;
    }
    
    // 计算本位的进位
    carry = (digitA + digitB + carry) >= 10 ? 1 : 0;
  }
  
  return false;
};

// 辅助函数：检查减法是否有借位
const hasBorrow = (a: number, b: number): boolean => {
  // 转换为字符串，便于按位检查
  const aStr = a.toString();
  const bStr = b.toString();
  
  let borrow = 0;
  // 从个位开始检查每一位
  for (let i = 0; i < Math.max(aStr.length, bStr.length); i++) {
    // 获取当前位的数字，不存在则为0
    const digitA = i < aStr.length ? parseInt(aStr[aStr.length - 1 - i]) : 0;
    const digitB = i < bStr.length ? parseInt(bStr[bStr.length - 1 - i]) : 0;
    
    // 判断是否需要借位
    if (digitA - borrow < digitB) {
      return true;
    }
    
    // 计算本位的借位
    borrow = (digitA - borrow < digitB) ? 1 : 0;
  }
  
  return false;
};

// 计算配置组的数字范围
const getConfigGroupRange = (group: ConfigGroup): number => {
  if (group.rangeType === 'custom') {
    return group.customRange;
  } else {
    return parseInt(group.rangeType, 10);
  }
};

// 根据位数限制生成数字
const generateNumberByDigits = (digitType: string, maxRange?: number): number => {
  let min, max;
  if (digitType === '1') {
    // 一位数：1-9
    min = 1;
    max = 9;
  } else if (digitType === '2') {
    // 两位数：10-99
    min = 10;
    max = 99;
  } else {
    // 任意位数：1到maxRange
    min = 1;
    max = maxRange || 100;
  }
  
  // 如果maxRange存在且小于计算出的max，使用maxRange
  if (maxRange && maxRange < max) {
    max = maxRange;
  }
  
  return generateRandomNumber(min, max);
};

// 获取数字的位数
const getDigitCount = (num: number): number => {
  return num.toString().length;
};

// 生成算式（支持传入配置）
const generateExpression = (type: string, useConfig?: ConfigGroup) => {
  // 如果传入了配置，使用配置；否则使用全局config
  const range = useConfig ? getConfigGroupRange(useConfig) : numberRangeValue.value;
  const noCarryAddition = useConfig ? useConfig.noCarryAddition : config.noCarryAddition;
  const noBorrowSubtraction = useConfig ? useConfig.noBorrowSubtraction : config.noBorrowSubtraction;
  const multiplicationTableLimit = useConfig ? useConfig.multiplicationTableLimit : config.multiplicationTableLimit;
  const allowRemainder = useConfig ? useConfig.allowRemainder : config.allowRemainder;
  const useDigitLimit = useConfig ? useConfig.useDigitLimit : config.useDigitLimit;
  const multiplicandDigits = useConfig ? useConfig.multiplicandDigits : config.multiplicandDigits;
  const multiplierDigits = useConfig ? useConfig.multiplierDigits : config.multiplierDigits;
  const dividendDigits = useConfig ? useConfig.dividendDigits : config.dividendDigits;
  const divisorDigits = useConfig ? useConfig.divisorDigits : config.divisorDigits;
  let num1, num2, result, expression, displayExpression;
  let attempts = 0;
  const maxAttempts = 100; // 防止无限循环
  let validExpression = false;
  
  do {
    attempts++;
    validExpression = false;
    
    switch (type) {
      case 'addition':
        num1 = generateRandomNumber(1, range);
        num2 = generateRandomNumber(1, range - num1);
        
        // 检查是否满足无进位加法的要求
        if (noCarryAddition) {
          validExpression = !hasCarry(num1, num2);
        } else {
          validExpression = true;
        }
        
        result = num1 + num2;
        expression = `${num1} + ${num2}`;
        displayExpression = `${num1} + ${num2} = `;
        break;
        
      case 'subtraction':
        // 更简单可靠的方法：确保减法中所有数字（被减数、减数和差）都在范围内
        // 先生成被减数，保证它不超过范围
        num1 = generateRandomNumber(1, range);
        // 再生成减数，确保它不超过被减数(否则结果为负)且不超过范围
        num2 = generateRandomNumber(1, Math.min(num1 - 1, range));
        // 计算结果
        result = num1 - num2;
        
        // 检查是否满足无退位减法的要求
        if (noBorrowSubtraction) {
          validExpression = !hasBorrow(num1, num2);
        } else {
          validExpression = true;
        }
        
        expression = `${num1} - ${num2}`;
        displayExpression = `${num1} - ${num2} = `;
        break;
        
      case 'multiplication':
        if (multiplicationTableLimit) {
          num1 = generateRandomNumber(1, 9);
          num2 = generateRandomNumber(1, 9);
          result = num1 * num2;
          validExpression = true;
        } else if (useDigitLimit) {
          // 使用位数限制
          num1 = generateNumberByDigits(multiplicandDigits, range);
          num2 = generateNumberByDigits(multiplierDigits, range);
          result = num1 * num2;
          // 验证位数是否符合要求
          const num1Digits = getDigitCount(num1);
          const num2Digits = getDigitCount(num2);
          const expectedNum1Digits = multiplicandDigits === '1' ? 1 : (multiplicandDigits === '2' ? 2 : null);
          const expectedNum2Digits = multiplierDigits === '1' ? 1 : (multiplierDigits === '2' ? 2 : null);
          
          validExpression = true;
          if (expectedNum1Digits !== null && num1Digits !== expectedNum1Digits) {
            validExpression = false;
          }
          if (expectedNum2Digits !== null && num2Digits !== expectedNum2Digits) {
            validExpression = false;
          }
          // 确保数字不超过范围
          if (num1 > range || num2 > range) {
            validExpression = false;
          }
        } else {
          // 限制乘积在范围内，而不是乘数
          // 生成两个数，确保乘积在范围内
          let maxNum1 = Math.floor(Math.sqrt(range));
          num1 = generateRandomNumber(1, maxNum1);
          let maxNum2 = Math.floor(range / num1);
          if (maxNum2 < 1) maxNum2 = 1;
          num2 = generateRandomNumber(1, maxNum2);
          result = num1 * num2;
          
          // 确保乘积在范围内
          if (result > range) {
            validExpression = false;
          } else {
            validExpression = true;
          }
        }
        expression = `${num1} * ${num2}`;
        displayExpression = `${num1} × ${num2} = `;
        break;
        
      case 'division':
        if (multiplicationTableLimit) {
          // 表内除法：限制在九九乘法表范围内（1-9）
          // 生成除数（1-9）和商（1-9），被除数 = 除数 × 商
          if (allowRemainder) {
            // 允许余数时，可以生成有余数的除法
            num2 = generateRandomNumber(1, 9);
            num1 = generateRandomNumber(1, 9);
            result = num1 / num2;
          } else {
            // 确保整除：生成除数（1-9）和商（1-9），被除数 = 除数 × 商
            num2 = generateRandomNumber(1, 9);
            const quotient = generateRandomNumber(1, 9);
            num1 = num2 * quotient;
            result = quotient;
          }
          validExpression = true;
        } else if (useDigitLimit) {
          // 使用位数限制
          if (allowRemainder) {
            // 允许余数
            num2 = generateNumberByDigits(divisorDigits, range);
            num1 = generateNumberByDigits(dividendDigits, range);
            result = num1 / num2;
          } else {
            // 确保整除
            num2 = generateNumberByDigits(divisorDigits, range);
            // 计算商的最大值，确保被除数不超过范围
            const maxQuotient = Math.floor(range / num2);
            if (maxQuotient < 1) {
              validExpression = false;
              break;
            }
            const quotient = generateRandomNumber(1, maxQuotient);
            num1 = num2 * quotient;
            result = quotient;
          }
          
          // 验证位数是否符合要求
          const num1Digits = getDigitCount(num1);
          const num2Digits = getDigitCount(num2);
          const expectedNum1Digits = dividendDigits === '1' ? 1 : (dividendDigits === '2' ? 2 : null);
          const expectedNum2Digits = divisorDigits === '1' ? 1 : (divisorDigits === '2' ? 2 : null);
          
          validExpression = true;
          if (expectedNum1Digits !== null && num1Digits !== expectedNum1Digits) {
            validExpression = false;
          }
          if (expectedNum2Digits !== null && num2Digits !== expectedNum2Digits) {
            validExpression = false;
          }
          // 确保被除数不超过范围
          if (num1 > range) {
            validExpression = false;
          }
        } else {
          // 非表内除法：使用原有逻辑
          if (allowRemainder) {
            num2 = generateRandomNumber(1, Math.min(10, range));
            num1 = generateRandomNumber(1, range);
          } else {
            // 确保整除
            num2 = generateRandomNumber(1, Math.min(10, range));
            const factor = generateRandomNumber(1, Math.floor(range / num2));
            num1 = num2 * factor;
          }
          result = num1 / num2;
          validExpression = true;
        }
        expression = `${num1} / ${num2}`;
        displayExpression = `${num1} ÷ ${num2} = `;
        break;
        
      default:
        return null;
    }
    
    // 如果尝试次数过多，放宽条件
    if (attempts >= maxAttempts) {
      console.warn('超过最大尝试次数，放宽条件生成算式');
      validExpression = true;
      break;
    }
    
    // 对加减法，结果必须在范围内 (乘法已经单独处理)
    if ((type === 'addition' || type === 'subtraction') && result > range) {
      validExpression = false;
    }
  } while (!validExpression);
  
  return {
    expression,
    answer: result,
    displayExpression
  };
};

// 根据配置组生成题目
const generateProblemsByConfig = (group: ConfigGroup) => {
  const operationTypes = [];
  if (group.operations.addition) {
    operationTypes.push('addition');
  }
  if (group.operations.subtraction) {
    operationTypes.push('subtraction');
  }
  if (group.operations.multiplication) {
    operationTypes.push('multiplication');
  }
  if (group.operations.division) {
    operationTypes.push('division');
  }
  
  if (operationTypes.length === 0) {
    operationTypes.push('addition'); // 默认加法
  }
  
  const count = group.count;
  const generatedExpressions = new Set();
  const result = [];
  const range = getConfigGroupRange(group);

  // 计算所有可能的唯一算式数量
  let maxUnique = Infinity;
  if (group.excludeDuplicates) {
    let uniqueSet = new Set();
    for (const type of operationTypes) {
      for (let i = 1; i <= range; i++) {
        for (let j = 1; j <= range; j++) {
          const problem = generateExpression(type, group);
          if (problem) {
            uniqueSet.add(problem.expression);
          }
        }
      }
    }
    maxUnique = uniqueSet.size;
    if (count > maxUnique) {
      $q.notify({
        message: `配置组${group.id}：最多只能生成${maxUnique}道不重复题目，已自动调整。`,
        color: 'warning',
        timeout: 3000
      });
    }
  }
  const finalCount = group.excludeDuplicates ? Math.min(count, maxUnique) : count;

  let tryCount = 0;
  const maxTry = finalCount * 20; // 防止极端死循环
  while (result.length < finalCount && tryCount < maxTry) {
    tryCount++;
    const type = operationTypes[Math.floor(Math.random() * operationTypes.length)];
    const problem = generateExpression(type, group);
    if (problem) {
      if (group.excludeDuplicates) {
        if (!generatedExpressions.has(problem.expression)) {
          generatedExpressions.add(problem.expression);
          result.push(problem);
        }
      } else {
        result.push(problem);
      }
    }
  }
  if (result.length < finalCount) {
    $q.notify({
      message: `配置组${group.id}：仅生成了${result.length}道题目，已达最大可能性。`,
      color: 'warning',
      timeout: 3000
    });
  }
  return result;
};

// 生成混合题目
const generateMixedProblems = () => {
  if (useMultiConfig.value) {
    // 多配置组模式
    const allProblems: Array<{
      expression: string,
      answer: number,
      displayExpression: string
    }> = [];
    
    if (configGroups.value.length === 0) {
      $q.notify({
        message: '请至少添加一个配置组',
        color: 'negative'
      });
      return;
    }
    
    // 按配置组分别生成题目
    for (const group of configGroups.value) {
      const groupProblems = generateProblemsByConfig(group);
      allProblems.push(...groupProblems);
    }
    
    problems.value = allProblems;
    $q.notify({
      message: `成功生成${allProblems.length}道题目！`,
      color: 'positive'
    });
  } else {
    // 单一配置模式（原有逻辑）
    const operationTypes = [];
    if (config.operations.addition) {
      operationTypes.push('addition');
    }
    if (config.operations.subtraction) {
      operationTypes.push('subtraction');
    }
    if (config.operations.multiplication) {
      operationTypes.push('multiplication');
    }
    if (config.operations.division) {
      operationTypes.push('division');
    }
    
    if (operationTypes.length === 0) {
      operationTypes.push('addition'); // 默认加法
    }
    
    const count = problemCountValue.value;
    const generatedExpressions = new Set();
    const result = [];

    // 新增：计算所有可能的唯一算式数量
    let maxUnique = Infinity;
    if (config.excludeDuplicates) {
      // 只支持加法/减法/乘法/除法单一或组合的情况
      let uniqueSet = new Set();
      for (const type of operationTypes) {
        for (let i = 1; i <= numberRangeValue.value; i++) {
          for (let j = 1; j <= numberRangeValue.value; j++) {
            const problem = generateExpression(type);
            if (problem) {
              uniqueSet.add(problem.expression);
            }
          }
        }
      }
      maxUnique = uniqueSet.size;
      // 如果题目数量大于最大唯一数，自动限制
      if (count > maxUnique) {
        $q.notify({
          message: `当前条件下最多只能生成${maxUnique}道不重复题目，已自动调整。`,
          color: 'warning',
          timeout: 4000
        });
      }
    }
    const finalCount = config.excludeDuplicates ? Math.min(count, maxUnique) : count;

    let tryCount = 0;
    const maxTry = finalCount * 20; // 防止极端死循环
    while (result.length < finalCount && tryCount < maxTry) {
      tryCount++;
      const type = operationTypes[Math.floor(Math.random() * operationTypes.length)];
      const problem = generateExpression(type);
      if (problem) {
        if (config.excludeDuplicates) {
          if (!generatedExpressions.has(problem.expression)) {
            generatedExpressions.add(problem.expression);
            result.push(problem);
          }
        } else {
          result.push(problem);
        }
      }
    }
    if (result.length < finalCount) {
      $q.notify({
        message: `仅生成了${result.length}道题目，已达最大可能性。`,
        color: 'warning',
        timeout: 4000
      });
    }
    problems.value = result;
  }
};

// 创建PDF文档定义
const createPDFDocDefinition = () => {
  // 在生成PDF前验证字体状态 - 只验证中文字体
  console.log('生成PDF前的字体状态:', {
    'vfs是否存在': !!pdfMake.vfs,
    'vfs中的字体': Object.keys(pdfMake.vfs),
    'SimSun字体是否存在': !!pdfMake.vfs[DEFAULT_FONT_NAME],
    'SimSun字体内容长度': pdfMake.vfs[DEFAULT_FONT_NAME]?.length
  });

  const content = [];


  // 标题
  const title = {
    text: '数学练习题',
    style: 'header',
    alignment: 'center',
    margin: [0, 0, 0, 15]
  };
  content.push(title);
  
  // 新增：统计信息行
  content.push({
    columns: [
      { text: `日期：`, alignment: 'left', width: '33%', fontSize: 12, margin: [0, 0, 0, 6] },
      { text: '用时：', alignment: 'center', width: '34%', fontSize: 12, margin: [0, 0, 0, 6] },
      { text: '正确率：', alignment: 'right', width: '33%', fontSize: 12, margin: [0, 0, 0, 6] }
    ],
    margin: [0, 0, 0, 8]
  });
  // 每页题目数
  const itemsPerPage = 50; // 你可以根据实际纸张和字号调整
  const columnCount = 2;
  const itemsPerColumn = itemsPerPage / columnCount;

  for (let pageStart = 0; pageStart < problems.value.length; pageStart += itemsPerPage) {
    // 当前页的题目
    const pageProblems = problems.value.slice(pageStart, pageStart + itemsPerPage);

    // 左右列
    const leftColumn = [];
    const rightColumn = [];
    for (let i = 0; i < itemsPerColumn; i++) {
      const leftIndex = i;
      const rightIndex = i + itemsPerColumn;
      if (pageProblems[leftIndex]) {
        leftColumn.push({
          text: `(${pageStart + leftIndex + 1}). ${pageProblems[leftIndex].displayExpression}`,
          margin: [0, 0, 0, 13]
        });
      }
      if (pageProblems[rightIndex]) {
        rightColumn.push({
          text: `(${pageStart + rightIndex + 1}). ${pageProblems[rightIndex].displayExpression}`,
          margin: [0, 0, 0, 13]
        });
      }
    }

    content.push({
      columns: [
        { width: '*', stack: leftColumn },
        { width: 10, text: '' },
        { width: '*', stack: rightColumn }
      ],
      columnGap: 10,
      // 除最后一页外都分页
      ...(pageStart + itemsPerPage < problems.value.length ? { pageBreak: 'after' } : {})
    });
  }
  
  // 只有勾选了"显示参考答案"时才添加答案页
  if (config.showAnswers) {
    // 添加答案页
    content.push({ text: '', pageBreak: 'before' });
    content.push({
      text: '参考答案',
      style: 'header',
      alignment: 'center',
      margin: [0, 0, 0, 15]
    });
    
    const answerColumns = [];
    for (let i = 0; i < columnCount; i++) {
      const columnItems = [];
      for (let j = 0; j < itemsPerColumn; j++) {
        const index = i * itemsPerColumn + j;
        if (index < problems.value.length) {
          columnItems.push({ 
            text: `(${index + 1}). ${problems.value[index].displayExpression}${problems.value[index].answer}`, 
            margin: [0, 0, 0, 12]
          });
        }
      }
      answerColumns.push({
        width: '*',
        stack: columnItems
      });
      
      if (i < columnCount - 1) {
        answerColumns.push({ width: 10, text: '' });
      }
    }
    
    content.push({ columns: answerColumns });
  }
  
  // 日期信息
  content.push({
    text: `生成日期：${new Date().toLocaleDateString()}`,
    alignment: 'right',
    fontSize: 8,
    margin: [0, 20, 0, 0]
  });
  
  const docDefinition = {
    content,
    pageSize: 'A4',
    pageMargins: [30, 30, 30, 30],
    defaultStyle: {
      font: 'SimSun',
      fontSize: 12
    },
    styles: {
      header: {
        fontSize: 16,
        bold: true,
        font: 'SimSun'
      }
    },
    fonts: pdfMake.fonts
  };

  // 只验证中文字体
  if (!pdfMake.vfs[DEFAULT_FONT_NAME]) {
    throw new Error('中文字体未正确加载，请刷新页面重试');
  }

  return docDefinition;
};

// 预览PDF
const previewPDF = async () => {
  if (problems.value.length === 0) {
    $q.notify({
      message: '请先生成题目',
      color: 'negative'
    });
    return;
  }
  
  try {
    // 只检查中文字体
    if (!pdfMake.vfs[DEFAULT_FONT_NAME]) {
      console.log('中文字体未加载，尝试重新加载');
      await loadChineseFont();
    }

    const docDefinition = createPDFDocDefinition();
    const pdfDocGenerator = pdfMake.createPdf(docDefinition);
    
    pdfDocGenerator.open();
  } catch (error) {
    console.error('PDF预览错误:', error);
    $q.notify({
      message: `PDF预览失败: ${(error as any).message}`,
      color: 'negative',
      timeout: 5000
    });
  }
};

// 生成并下载PDF
const generatePDF = async () => {
  if (problems.value.length === 0) {
    $q.notify({
      message: '请先生成题目',
      color: 'negative'
    });
    return;
  }
  
  try {
    $q.notify({
      message: '正在生成PDF，请稍候...',
      color: 'info'
    });
    
    // 检查字体状态
    if (!pdfMake.vfs[DEFAULT_FONT_NAME]) {
      // 尝试加载字体（如果尚未加载）
      console.log('PDF生成前发现字体未加载，尝试重新加载');
      const fontLoaded = await loadChineseFont();
      if (!fontLoaded) {
        // 字体加载失败，询问是否继续
        const continueWithoutFont = await $q.dialog({
          title: '中文字体未加载',
          message: '中文字体加载失败，PDF中的中文可能无法正确显示。是否继续？',
          cancel: true,
          persistent: true
        }).onOk(() => true).onCancel(() => false);
        
        if (!continueWithoutFont) {
          return;
        }
      }
    }
    
    // 创建PDF文档
    const docDefinition = createPDFDocDefinition();
    const pdfDocGenerator = pdfMake.createPdf(docDefinition);
    
    // 生成PDF的Blob形式并创建下载链接
    pdfDocGenerator.getBlob((blob: Blob) => {
      // 创建Blob链接
      const url = URL.createObjectURL(blob);
      
      // 生成带时间戳的文件名
      const now = new Date();
      const timestamp = now.getFullYear().toString() +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        now.getDate().toString().padStart(2, '0') + '_' +
        now.getHours().toString().padStart(2, '0') +
        now.getMinutes().toString().padStart(2, '0') +
        now.getSeconds().toString().padStart(2, '0');
      const fileName = `口算练习_${timestamp}.pdf`;
      
      // 创建一个看不见的<a>标签用于下载
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = fileName;
      
      // 添加到文档中并触发点击
      document.body.appendChild(a);
      a.click();
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 100);
      
      $q.notify({
        message: 'PDF生成并下载成功!',
        color: 'positive'
      });
    });
  } catch (error) {
    console.error('PDF生成错误:', error);
    $q.notify({
      message: `PDF生成失败: ${(error as any).message}`,
      color: 'negative',
      timeout: 5000
    });
  }
};

// 配置组管理函数
const addConfigGroup = () => {
  configGroups.value.push({
    id: nextConfigGroupId++,
    count: 20,
    customRange: 100,
    rangeType: '100',
    operations: {
      addition: true,
      subtraction: true,
      multiplication: false,
      division: false
    },
    excludeDuplicates: true,
    allowRemainder: false,
    multiplicationTableLimit: false,
    noCarryAddition: false,
    noBorrowSubtraction: false,
    useDigitLimit: false,
    multiplicandDigits: 'any',
    multiplierDigits: 'any',
    dividendDigits: 'any',
    divisorDigits: 'any'
  });
};

const removeConfigGroup = (id: number) => {
  const index = configGroups.value.findIndex(g => g.id === id);
  if (index > -1) {
    configGroups.value.splice(index, 1);
  }
};

// 计算总题目数
const totalProblemCount = computed(() => {
  if (useMultiConfig.value) {
    return configGroups.value.reduce((sum, group) => sum + group.count, 0);
  }
  return problemCountValue.value;
});

// 开始生成题目
const startGenerate = () => {
  generateMixedProblems();
};

// 开始在线答题
const startOnlinePractice = () => {
  if (problems.value.length === 0) {
    $q.notify({
      message: '请先生成题目',
      color: 'negative'
    });
    return;
  }

  if (!userStore.currentUser) {
    $q.dialog({
      title: '需要登录',
      message: '请先登录后再进行在线答题',
      ok: {
        label: '去登录',
        color: 'primary'
      },
      cancel: {
        label: '取消',
        color: 'negative'
      },
      persistent: true
    }).onOk(() => {
      // 使用router进行导航
      router.push('/login');
    });
    return;
  }

  showProblemSolver.value = true;
};

// 提交反馈
const submitFeedback = () => {
  if (!feedbackContent.value.trim()) {
    $q.notify({
      message: '请输入反馈内容',
      color: 'negative'
    });
    return;
  }
  
  // 这里可以添加发送反馈到服务器的逻辑
  console.log('反馈内容:', feedbackContent.value);
  console.log('联系邮箱:', feedbackEmail.value);
  
  $q.notify({
    message: '感谢您的反馈！',
    color: 'positive'
  });
  
  // 清空表单并关闭对话框
  feedbackContent.value = '';
  feedbackEmail.value = '';
  showFeedbackDialog.value = false;
};
</script>

<template>
  <q-card flat bordered>
    <q-card-section class="text-h6">
      智能出题系统
    </q-card-section>
    
    <q-card-section>
      <!-- 模式选择 -->
      <q-item>
        <q-item-section>
          <q-item-label>出题模式</q-item-label>
          <div class="row q-gutter-md">
            <q-radio v-model="useMultiConfig" :val="false" label="单一配置" />
            <q-radio v-model="useMultiConfig" :val="true" label="多配置组" />
          </div>
          <div v-if="useMultiConfig" class="q-mt-sm text-caption text-grey">
            共 {{ totalProblemCount }} 题
          </div>
        </q-item-section>
      </q-item>
      
      <q-separator class="q-my-md" />
      
      <!-- 多配置组模式 -->
      <div v-if="useMultiConfig">
        <div v-for="group in configGroups" :key="group.id" class="q-mb-md">
          <q-card flat bordered class="q-pa-md">
            <div class="row items-center q-mb-sm">
              <div class="text-subtitle2">配置组 {{ group.id }}</div>
              <q-space />
              <q-btn 
                flat 
                round 
                dense 
                icon="delete" 
                color="negative" 
                @click="removeConfigGroup(group.id)"
                :disable="configGroups.length <= 1"
              />
            </div>
            
            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-xs-12">
                <!-- 题目数量 -->
                <q-input
                  v-model.number="group.count"
                  type="number"
                  label="题目数量"
                  min="1"
                  max="10000"
                  outlined
                  dense
                  class="q-mb-sm"
                />
                
                <!-- 数字范围 -->
                <q-item-label class="q-mb-xs">数字范围</q-item-label>
                <div class="row justify-start q-gutter-md q-mb-sm">
                  <q-radio v-model="group.rangeType" val="10" label="10以内" />
                  <q-radio v-model="group.rangeType" val="20" label="20以内" />
                  <q-radio v-model="group.rangeType" val="100" label="100以内" />
                  <q-radio v-model="group.rangeType" val="custom" label="自定义" />
                </div>
                
                <q-input
                  v-if="group.rangeType === 'custom'"
                  v-model.number="group.customRange"
                  type="number"
                  label="自定义数值范围"
                  min="1"
                  max="10000"
                  outlined
                  dense
                  class="q-mb-sm"
                />
              </div>
              
              <div class="col-md-6 col-xs-12">
                <!-- 运算类型 -->
                <q-item-label class="q-mb-xs">运算类型</q-item-label>
                <div class="q-gutter-sm q-mb-sm">
                  <q-checkbox v-model="group.operations.addition" label="加法" />
                  <q-checkbox v-model="group.operations.subtraction" label="减法" />
                  <q-checkbox v-model="group.operations.multiplication" label="乘法" />
                  <q-checkbox v-model="group.operations.division" label="除法" />
                </div>
                
                <!-- 特殊设置 -->
                <div class="q-gutter-sm">
                  <q-checkbox v-model="group.excludeDuplicates" label="排除重复算式" />
                  <div v-if="group.operations.addition">
                    <q-checkbox v-model="group.noCarryAddition" label="无进位加法" />
                  </div>
                  <div v-if="group.operations.subtraction">
                    <q-checkbox v-model="group.noBorrowSubtraction" label="无退位减法" />
                  </div>
                  <div v-if="group.operations.division">
                    <q-checkbox 
                      v-model="group.allowRemainder" 
                      label="除法允许余数" 
                    />
                  </div>
                  <div v-if="group.operations.multiplication || group.operations.division">
                    <q-checkbox 
                      v-model="group.multiplicationTableLimit" 
                      label="限制在九九乘法表范围（乘除法）"
                    />
                  </div>
                  <div v-if="(group.operations.multiplication || group.operations.division) && !group.multiplicationTableLimit">
                    <q-checkbox 
                      v-model="group.useDigitLimit" 
                      label="使用位数限制"
                    />
                  </div>
                  <div v-if="group.useDigitLimit && group.operations.multiplication" class="q-ml-md q-mt-xs">
                    <div class="row q-gutter-sm items-center">
                      <span class="text-caption">被乘数：</span>
                      <q-radio v-model="group.multiplicandDigits" val="1" label="一位数" dense />
                      <q-radio v-model="group.multiplicandDigits" val="2" label="两位数" dense />
                      <q-radio v-model="group.multiplicandDigits" val="any" label="任意" dense />
                    </div>
                    <div class="row q-gutter-sm items-center q-mt-xs">
                      <span class="text-caption">乘数：</span>
                      <q-radio v-model="group.multiplierDigits" val="1" label="一位数" dense />
                      <q-radio v-model="group.multiplierDigits" val="2" label="两位数" dense />
                      <q-radio v-model="group.multiplierDigits" val="any" label="任意" dense />
                    </div>
                  </div>
                  <div v-if="group.useDigitLimit && group.operations.division" class="q-ml-md q-mt-xs">
                    <div class="row q-gutter-sm items-center">
                      <span class="text-caption">被除数：</span>
                      <q-radio v-model="group.dividendDigits" val="1" label="一位数" dense />
                      <q-radio v-model="group.dividendDigits" val="2" label="两位数" dense />
                      <q-radio v-model="group.dividendDigits" val="any" label="任意" dense />
                    </div>
                    <div class="row q-gutter-sm items-center q-mt-xs">
                      <span class="text-caption">除数：</span>
                      <q-radio v-model="group.divisorDigits" val="1" label="一位数" dense />
                      <q-radio v-model="group.divisorDigits" val="2" label="两位数" dense />
                      <q-radio v-model="group.divisorDigits" val="any" label="任意" dense />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </q-card>
        </div>
        
        <div class="q-mt-md">
          <q-btn 
            color="primary" 
            outline 
            icon="add" 
            label="添加配置组" 
            @click="addConfigGroup"
          />
        </div>
      </div>
      
      <!-- 单一配置模式 -->
      <div v-else>
        <div class="row q-col-gutter-md">
        <div class="col-md-6 col-xs-12">
          <!-- 数字范围 -->
          <q-item>
            <q-item-section>
              <q-item-label>数字范围</q-item-label>
              <div class="row justify-center q-gutter-md">
                <q-radio v-model="config.rangeType" val="10" label="10以内" />
                <q-radio v-model="config.rangeType" val="20" label="20以内" />
                <q-radio v-model="config.rangeType" val="100" label="100以内" />
                <q-radio v-model="config.rangeType" val="custom" label="自定义" />
              </div>
              
              <q-input
                v-if="config.rangeType === 'custom'"
                v-model.number="config.customRange"
                type="number"
                label="自定义数值范围"
                min="1"
                max="10000"
                outlined
                dense
                class="q-mt-sm"
              />
            </q-item-section>
          </q-item>
          
          <!-- 运算类型 -->
          <q-item>
            <q-item-section>
              <q-item-label>运算类型</q-item-label>
              <div class="q-gutter-sm">
                <q-checkbox v-model="config.operations.addition" label="加法" />
                <q-checkbox v-model="config.operations.subtraction" label="减法" />
                <q-checkbox v-model="config.operations.multiplication" label="乘法" />
                <q-checkbox v-model="config.operations.division" label="除法" />
              </div>
            </q-item-section>
          </q-item>
        </div>
        
        <div class="col-md-6 col-xs-12">
          <!-- 题目数量 -->
          <q-item>
            <q-item-section>
              <q-item-label>题目数量</q-item-label>
              <div class="row justify-center q-gutter-md">
                <q-radio v-model="config.countType" val="20" label="20题" />
                <q-radio v-model="config.countType" val="50" label="50题" />
                <q-radio v-model="config.countType" val="100" label="100题" />
                <q-radio v-model="config.countType" val="custom" label="自定义" />
              </div>
              
              <q-input
                v-if="config.countType === 'custom'"
                v-model.number="config.customCount"
                type="number"
                label="自定义题目数量"
                min="1"
                max="10000"
                outlined
                dense
                class="q-mt-sm"
              />
            </q-item-section>
          </q-item>
          
          <!-- 特殊设置 -->
          <q-item>
            <q-item-section>
              <q-item-label>特殊设置</q-item-label>
              <div>
                <q-checkbox v-model="config.excludeDuplicates" label="排除重复算式" />
              </div>
              <div v-if="config.operations.addition">
                <q-checkbox v-model="config.noCarryAddition" label="无进位加法" />
              </div>
              <div v-if="config.operations.subtraction">
                <q-checkbox v-model="config.noBorrowSubtraction" label="无退位减法" />
              </div>
              <div v-if="config.operations.division">
                <q-checkbox 
                  v-model="config.allowRemainder" 
                  label="除法允许余数" 
                />
              </div>
              <div v-if="config.operations.multiplication || config.operations.division">
                <q-checkbox 
                  v-model="config.multiplicationTableLimit" 
                  label="限制在九九乘法表范围（乘除法）"
                />
              </div>
              <div v-if="(config.operations.multiplication || config.operations.division) && !config.multiplicationTableLimit">
                <q-checkbox 
                  v-model="config.useDigitLimit" 
                  label="使用位数限制"
                />
              </div>
              <div v-if="config.useDigitLimit && config.operations.multiplication" class="q-ml-md q-mt-xs">
                <div class="row q-gutter-sm items-center">
                  <span class="text-caption">被乘数：</span>
                  <q-radio v-model="config.multiplicandDigits" val="1" label="一位数" dense />
                  <q-radio v-model="config.multiplicandDigits" val="2" label="两位数" dense />
                  <q-radio v-model="config.multiplicandDigits" val="any" label="任意" dense />
                </div>
                <div class="row q-gutter-sm items-center q-mt-xs">
                  <span class="text-caption">乘数：</span>
                  <q-radio v-model="config.multiplierDigits" val="1" label="一位数" dense />
                  <q-radio v-model="config.multiplierDigits" val="2" label="两位数" dense />
                  <q-radio v-model="config.multiplierDigits" val="any" label="任意" dense />
                </div>
              </div>
              <div v-if="config.useDigitLimit && config.operations.division" class="q-ml-md q-mt-xs">
                <div class="row q-gutter-sm items-center">
                  <span class="text-caption">被除数：</span>
                  <q-radio v-model="config.dividendDigits" val="1" label="一位数" dense />
                  <q-radio v-model="config.dividendDigits" val="2" label="两位数" dense />
                  <q-radio v-model="config.dividendDigits" val="any" label="任意" dense />
                </div>
                <div class="row q-gutter-sm items-center q-mt-xs">
                  <span class="text-caption">除数：</span>
                  <q-radio v-model="config.divisorDigits" val="1" label="一位数" dense />
                  <q-radio v-model="config.divisorDigits" val="2" label="两位数" dense />
                  <q-radio v-model="config.divisorDigits" val="any" label="任意" dense />
                </div>
              </div>
              <div>
                <q-checkbox v-model="config.showAnswers" label="显示参考答案" />
              </div>
            </q-item-section>
          </q-item>
        </div>
      </div>
      </div>
    </q-card-section>
    
    <q-card-actions align="center">
      <div class="row q-col-gutter-sm justify-center full-width">
        <div class="col-auto">
          <q-btn color="primary" label="生成题目" @click="startGenerate" />
        </div>
        <div class="col-auto">
          <q-btn color="secondary" label="在线答题" @click="startOnlinePractice" :disable="problems.length === 0" />
        </div>
        <div class="col-auto">
          <q-btn color="secondary" label="预览PDF" @click="previewPDF" :disable="problems.length === 0" />
        </div>
        <div class="col-auto">
          <q-btn color="secondary" label="下载PDF" @click="generatePDF" :disable="problems.length === 0" />
        </div>
      </div>
    </q-card-actions>
    
    <!-- 预览区域 -->
    <q-card-section v-if="problems.length > 0">
      <q-separator class="q-mb-md" />
      <div class="text-subtitle1 q-mb-sm">题目预览：</div>
      <div class="row q-col-gutter-md">
        <div 
          v-for="(problem, index) in problems.slice(0, 10)" 
          :key="index"
          class="col-md-3 col-sm-4 col-xs-6"
        >
          <div class="problem-item q-pa-sm">
            {{ index + 1 }}. {{ problem.displayExpression }}
          </div>
        </div>
      </div>
      <div class="text-center q-mt-md" v-if="problems.length > 10">
        <q-chip outline color="grey">显示前10题，共{{ problems.length }}题</q-chip>
      </div>
    </q-card-section>

    <!-- 添加反馈对话框 -->
    <q-dialog v-model="showFeedbackDialog">
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">反馈意见</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-input
            v-model="feedbackContent"
            type="textarea"
            label="请输入您的反馈意见"
            :rules="[val => !!val || '请输入反馈内容']"
            autogrow
          />
          <q-input
            v-model="feedbackEmail"
            type="email"
            label="联系邮箱（选填）"
            class="q-mt-md"
          />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn flat label="提交" @click="submitFeedback" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 添加使用说明对话框 -->
    <q-dialog v-model="showInstructionsDialog">
      <q-card style="min-width: 350px; max-width: 600px">
        <q-card-section>
          <div class="text-h6">使用说明</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <div class="text-body2">
            <p><strong>1. 基本设置</strong></p>
            <ul>
              <li>选择数字范围：可以选择10以内、20以内、100以内或自定义范围</li>
              <li>选择运算类型：支持加法、减法、乘法和除法</li>
              <li>设置题目数量：可以选择20题、50题、100题或自定义数量</li>
            </ul>

            <p><strong>2. 特殊设置</strong></p>
            <ul>
              <li>排除重复算式：避免生成重复的题目</li>
              <li>无进位加法：生成的加法题目不涉及进位</li>
              <li>无退位减法：生成的减法题目不涉及退位</li>
              <li>除法允许余数：生成的除法题目可以有余数</li>
              <li>限制在九九乘法表范围：乘法题目限制在乘法表范围内</li>
              <li>显示参考答案：可以选择是否显示答案</li>
            </ul>

            <p><strong>3. 导出功能</strong></p>
            <ul>
              <li>预览PDF：可以在线预览生成的题目</li>
              <li>下载PDF：可以将题目下载为PDF文件</li>
            </ul>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="关闭" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 添加在线答题对话框 -->
    <q-dialog v-model="showProblemSolver" full-width persistent>
      <q-card style="min-width: 350px">
        <q-card-section>
          <problem-solver
            :problems="problems"
            @close="showProblemSolver = false"
          />
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-card>
</template>

<style scoped>
.problem-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  min-height: 50px;
  display: flex;
  align-items: center;
}
</style> 